package structures.queue;

import java.util.Scanner;

public class CircleArrayDemo {
    public static void main(String[] args) {
        // 创建队列
        CircleArray arrayQueue = new CircleArray(4);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println();
            System.out.println("s(show) 显示队列全部数据");
            System.out.println("e(exit) 退出程序");
            System.out.println("a(add) 添加数据");
            System.out.println("g(get) 获取数据");
            System.out.println("h(head) 查看头部数据");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    arrayQueue.showQueueArray();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                case 'a':
                    int data = scanner.nextInt();
                    arrayQueue.addData(data);
                    break;
                case 'g':
                    System.out.println(arrayQueue.getData());
                    break;
                case 'h':
                    System.out.println(arrayQueue.catHeadData());
                    break;
            }
            System.out.println("------------------------");
        }
    }
}

class CircleArray {
    // 数据头位置
    private int front;
    // 数据尾  若队列不为空,则指向队列尾元素的下一个位置
    private int rear;
    // 数据空间大小
    private final int maxSize;
    // 数据列表
    private final int[] arr;

    public CircleArray(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
    }

    //判空
    public boolean isEmpty() {
        return front == rear;
    }

    // 判满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 添加数据
    public void addData(int data) {
        if (isFull()) {
            System.out.println("队列已满, 添加数据失败");
            return;
        }
        arr[rear] = data;
        rear = (rear + 1) % maxSize;
    }

    // 获取数据
    public int getData() {
        if (isEmpty()) {
            System.out.println("获取数据失败, 列表为空");
            return -1;
        }
        int data = arr[front];
        front = (front + 1) % maxSize;
        return data;
    }

    // 显示整个列表
    public void showQueueArray() {
        if (isEmpty()) {
            System.out.println("列表为空, 遍历列表失败");
            return;
        }
        for (int index = front; index < front + getLength(); index++) {
            System.out.println("arr[" + index % maxSize + "] = " + arr[index % maxSize]);
        }
    }

    // 获取头数据,不进行移除操作
    public int catHeadData() {
        if (isEmpty()) {
            System.out.println("获取数据失败, 列表为空");
            return -1;
        }
        return arr[front];
    }

    public int getLength() {
        return (rear - front + maxSize) % maxSize;
    }
}
